<template>
  <div class="p-login-container">
    <a-flex vertical class="p-login-form-container">
      <div class="p-login-form-content">
        <a-flex vertical justify="center" align="center">
          <div class="p-login-form-content__logo-container">
            <img
              src="@/assets/logo.png"
              alt="logo"
              class="p-login-form-content__logo"
            />
            <img
              src="@/assets/logo-name.png"
              alt="可乐白板"
              class="p-login-form-content__banner"
            />
          </div>
          <div class="p-login-form-content__subtitle">
            在线协作白板，团队效率工具
          </div>
        </a-flex>
        <div class="p-login-form-content__form">
          <a-form :model="loginForm" :rules="rules" ref="loginFormRef">
            <a-form-item name="username">
              <a-input-group compact size="large">
                <a-form-item-rest>
                  <a-select v-model:value="loginForm.prefix" style="width: 40%">
                    <a-select-option value="86">+86（中国）</a-select-option>
                  </a-select>
                </a-form-item-rest>
                <a-input
                  v-model:value="loginForm.username"
                  placeholder="手机号"
                  style="width: 60%"
                />
              </a-input-group>
            </a-form-item>
            <a-form-item v-if="loginState.method" name="password">
              <a-input-password
                v-model:value="loginForm.password"
                placeholder="密码"
                size="large"
              />
            </a-form-item>
            <a-form-item v-else name="verifyCode">
              <a-input-group compact size="large">
                <a-input
                  v-model:value="loginForm.verifyCode"
                  placeholder="验证码"
                  style="width: 60%"
                />
                <a-button
                  style="width: 40%"
                  @click="getVerifyCode"
                  :disabled="verifyCodeBtn.disabled"
                  :loading="verifyCodeBtn.loading"
                >
                  <span style="font-size: 0.8rem">
                    {{ verifyCodeBtn.text }}
                  </span>
                </a-button>
              </a-input-group>
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 24 }">
              <a-button
                type="primary"
                block
                size="large"
                @click="login"
                :loading="loginState.loginLoading"
              >
                {{ loginState.method ? '登录' : '登录/注册' }}
              </a-button>
              <a-flex
                :justify="loginState.method ? 'space-between' : 'center'"
                align="center"
                style="margin-top: 8px"
              >
                <template v-if="loginState.method">
                  <span
                    class="p-login-form-content__form-link"
                    @click="changeLoginMethod(false)"
                  >
                    验证码登录/注册
                  </span>
                  <span
                    class="p-login-form-content__form-link"
                    @click="changeLoginMethod(false)"
                  >
                    忘记密码
                  </span>
                </template>
                <template v-else>
                  <span
                    class="p-login-form-content__form-link"
                    @click="changeLoginMethod(true)"
                  >
                    密码登录
                  </span>
                </template>
              </a-flex>
            </a-form-item>
          </a-form>
        </div>
      </div>
    </a-flex>
    <div class="p-login-footer">
      <a href="https://beian.miit.gov.cn/" target="_blank" class="link">
        粤ICP备2024211615号
      </a>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onBeforeMount } from 'vue';
import {
  validateUsername,
  validatePassword,
  validateVerifyCode,
} from '@/utils/FormRules.ts';
import { Rule } from 'ant-design-vue/es/form';
import operateAccount from '@/apis/operate-account.ts';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useAccountStore } from '@/store/index.ts';

const router = useRouter();
const userStore = useAccountStore();

onBeforeMount(async () => {
  try {
    const res = await operateAccount.checkLoginStatus();
    if (res.data) {
      message.info('检测到您已登录，自动跳转至工作台');
      await router.push({ name: 'workbench' });
    }
  } catch (e) {
    console.error(e);
  }
});

// 登录表单校验规则
const rules: Record<string, Rule[]> = {
  username: [{ validator: validateUsername, trigger: ['blur', 'change'] }],
  password: [{ validator: validatePassword, trigger: ['blur', 'change'] }],
  verifyCode: [{ validator: validateVerifyCode, trigger: ['blur', 'change'] }],
};

const loginFormRef = ref(null);
const loginForm = reactive({
  prefix: '86',
  username: '',
  password: '',
  verifyCode: '',
});
const loginState = reactive({
  loginLoading: false, // 登录按钮防抖
  method: true, // 登录方式，false = 手机验证码登录，true = 账号密码登录
});
// 修改登录方式
function changeLoginMethod(method: boolean) {
  loginState.method = method;
  loginFormRef.value.clearValidate(['password', 'verifyCode']);
  loginFormRef.value.resetFields(['password', 'verifyCode']);
}

// 登录
function login() {
  loginState.loginLoading = true;
  let validateFields: string[];
  if (loginState.method) {
    validateFields = ['username', 'password'];
  } else {
    validateFields = ['username', 'verifyCode'];
  }
  loginFormRef.value
    .validateFields(validateFields)
    .then(async (res: any) => {
      let response;
      if (loginState.method) {
        response = await operateAccount.registerByPassword({
          username: res.username,
          password: res.password,
        });
      } else {
        response = await operateAccount.signUpOrRegisterByVerifyCode({
          phoneNum: res.username,
          verifyCode: res.verifyCode,
        });
      }
      if (response.msg === '操作成功') {
        // 登录成功后保存 token 至 store 和 localStorage 里
        userStore.setUserToken(response.data);
        message.success('登录成功');
        loginState.loginLoading = false;
        await router.push({ name: 'workbench' });
      }
      loginState.loginLoading = false;
    })
    .catch((err: any) => {
      loginState.loginLoading = false;
      console.log(err);
    });
}

const verifyCodeBtn = reactive({
  text: '获取短信验证码',
  disabled: false,
  loading: false,
});
// 获取登录短信验证码
function getVerifyCode() {
  verifyCodeBtn.loading = true;
  loginFormRef.value
    .validateFields(['username'])
    .then(async (res: any) => {
      // 校验成功后请求 获取短信验证码接口
      const response = await operateAccount.getVerifyCode({
        phoneNum: res.username,
      });
      if (response.msg === '发送成功') {
        verifyCodeBtn.loading = false;
        message.success('验证码发送成功');
        // 获取成功后缓冲60s
        let timer = 60;
        verifyCodeBtn.disabled = true;
        verifyCodeBtn.text = '验证码（' + timer + 's）';
        const timeFun = setInterval(() => {
          --timer;
          verifyCodeBtn.text = '验证码（' + timer + 's）';
          if (timer == 0) {
            verifyCodeBtn.text = '获取短信验证码';
            verifyCodeBtn.disabled = false;
            clearInterval(timeFun);
          }
        }, 1000);
      }
      verifyCodeBtn.loading = false;
    })
    .catch((err) => {
      verifyCodeBtn.loading = false;
      console.log(err);
    });
}
</script>

<style scoped lang="scss">
.p-login-container {
  width: 100%;
  height: 100%;
  position: relative;
  background: radial-gradient(
      66.06% 66.06% at 0 0,
      rgba(255, 122, 146, 0.16) 0,
      rgba(255, 122, 146, 0) 100%
    ),
    radial-gradient(
      46.32% 67.56% at 52.35% -1%,
      rgba(52, 86, 255, 0.1) 0,
      rgba(52, 86, 255, 0) 100%
    ),
    radial-gradient(
      59.31% 62.11% at 92.4% 0,
      rgba(122, 247, 255, 0.1) 0,
      rgba(122, 247, 255, 0) 100%
    );
  .p-login-form-container {
    min-width: 420px;
    //min-height: 705px;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translateX(-50%) translateY(-50%);
    .p-login-form-content {
      background: #fff;
      padding: 30px 30px 0 30px;
      border-radius: 5px;
      box-shadow: 0 0 10px 0 rgba(178, 178, 178, 0.3);
      .p-login-form-content__logo-container {
        .p-login-form-content__logo {
          pointer-events: none;
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
          width: 3rem;
          height: 3rem;
        }
        .p-login-form-content__banner {
          pointer-events: none;
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
          width: 10rem;
          height: 4rem;
        }
      }
      .p-login-form-content__subtitle {
        color: #878b90;
        font-size: 1rem;
        margin: 20px 0 30px 0;
      }
    }
    .p-login-form-footer {
      height: 50px;
    }
    .p-login-form-content__form-link {
      color: #8f8b8b;
      font-size: 0.9rem;
      cursor: pointer;
      -webkit-user-select: none;
      -moz-user-select: none;
      -ms-user-select: none;
      user-select: none;
    }
    .p-login-form-content__form-link-no-pointer {
      cursor: default;
    }
  }
  .p-login-footer {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 10px;
    .link {
      color: #6A6A6A;
      text-decoration: none;
    }
  }
}
</style>
